<template>
  <el-dialog 
    :model-value="modelValue" 
    @update:model-value="$emit('update:modelValue', $event)"
    :title="title"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="date-picker-content">
      <div class="date-info">
        <p class="info-text">{{ infoText }}</p>
        <p class="range-hint">{{ rangeHint }}</p>
      </div>
      
      <div class="date-picker-wrapper">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          :placeholder="placeholder"
          style="width: 100%"
          size="large"
          :disabled-date="disabledDate"
          :default-value="defaultDisplayDate"
          @change="onDateChange"
        />
      </div>
      
      <div class="validation-message" v-if="validationMessage">
        <el-alert
          :title="validationMessage"
          type="warning"
          :closable="false"
          show-icon
        />
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :disabled="!selectedDate"
          :loading="loading"
        >
          {{ loading ? '保存中...' : '确定' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '选择日期'
  },
  infoText: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择日期'
  },
  dateRange: {
    type: Object,
    default: null
  },
  presetDate: {
    type: String,
    default: null
  },
  referenceDate: {
    type: String,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const selectedDate = ref('')
const loading = ref(false)
const validationMessage = ref('')

const rangeHint = computed(() => {
  if (!props.dateRange) return ''
  return `可选范围：${props.dateRange.minDate} 至 ${props.dateRange.maxDate}`
})

// 计算默认显示的日期（用于日历面板显示哪个月）
const defaultDisplayDate = computed(() => {
  // 如果有参考日期（如开始日期），使用参考日期的月份
  if (props.referenceDate) {
    return new Date(props.referenceDate)
  }
  
  // 如果有日期范围，使用范围的中间日期
  if (props.dateRange && props.dateRange.minDate) {
    return new Date(props.dateRange.minDate)
  }
  
  // 默认使用当前日期
  return new Date()
})

// 监听对话框打开，初始化日期
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    selectedDate.value = props.presetDate || ''
    validationMessage.value = ''
    loading.value = false
  }
})

// 禁用日期的逻辑
const disabledDate = (date) => {
  const today = new Date()
  today.setHours(23, 59, 59, 999)
  
  // 不能超过今天
  if (date > today) return true
  
  // 如果有日期范围限制
  if (props.dateRange) {
    const dateStr = formatDate(date)
    return dateStr < props.dateRange.minDate || dateStr > props.dateRange.maxDate
  }
  
  return false
}

const onDateChange = (date) => {
  validationMessage.value = ''
}

const handleCancel = () => {
  emit('update:modelValue', false)
  selectedDate.value = ''
  validationMessage.value = ''
}

const handleConfirm = async () => {
  if (!selectedDate.value) {
    validationMessage.value = '请选择日期'
    return
  }
  
  try {
    loading.value = true
    const dateStr = formatDate(selectedDate.value)
    
    // 验证日期是否在允许范围内
    if (props.dateRange) {
      if (dateStr < props.dateRange.minDate || dateStr > props.dateRange.maxDate) {
        validationMessage.value = `日期必须在${props.dateRange.minDate}到${props.dateRange.maxDate}之间`
        return
      }
    }
    
    emit('confirm', dateStr)
    emit('update:modelValue', false)
    selectedDate.value = ''
    validationMessage.value = ''
  } catch (error) {
    validationMessage.value = '操作失败，请重试'
  } finally {
    loading.value = false
  }
}

const formatDate = (date) => {
  if (typeof date === 'string') return date
  if (date instanceof Date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  return date
}
</script>

<style scoped>
.date-picker-content {
  padding: 10px 0;
}

.date-info {
  margin-bottom: 20px;
  text-align: center;
}

.info-text {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.range-hint {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.date-picker-wrapper {
  margin-bottom: 16px;
}

.validation-message {
  margin-top: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-date-editor) {
  height: 48px;
  font-size: 16px;
}

:deep(.el-input__inner) {
  text-align: center;
}
</style>
